package com.wz.base.support.events.publisher;

import com.wz.base.support.events.DomainEvent;
import com.wz.base.support.events.DomainEventPublisher;
import io.vavr.collection.List;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

public class StoreAndForwardDomainEventPublisher implements DomainEventPublisher {

    private final DomainEventPublisher eventsPublisher;
    private final EventsStorage eventsStorage;

    public StoreAndForwardDomainEventPublisher(DomainEventPublisher eventsPublisher, EventsStorage eventsStorage) {
        this.eventsPublisher = eventsPublisher;
        this.eventsStorage = eventsStorage;
    }

    @Override
    public void publish(DomainEvent event) {
        eventsStorage.save(event);
    }

    @Scheduled(fixedRate = 3000L)
    @Transactional
    public void publishAllPeriodically() {
        List<DomainEvent> domainEvents = eventsStorage.toPublish();
        domainEvents.forEach(eventsPublisher::publish);
        eventsStorage.published(domainEvents);
    }
}
